# -*- coding: utf-8 -*-
# Create your views here.
from django.shortcuts import render_to_response, get_object_or_404, get_list_or_404
from django import forms
from django.http import HttpResponseRedirect, HttpResponse, Http404
from django.template import RequestContext
import os
from django.contrib.auth.decorators import login_required
import sys
from docs.models import *

@login_required
def project_list(request):
    project_objects = Project.objects.extra(select = {'people_count': 'SELECT COUNT(*) FROM `auth_user` INNER JOIN `docs_project_translators` ON (`auth_user`.`id` = `docs_project_translators`.`user_id`) WHERE `docs_project_translators`.`project_id` = `docs_project`.`id`',
                                                      'page_count': 'SELECT COUNT(*) FROM `docs_page` WHERE (`docs_page`.`project_id` = `docs_project`.`id` AND `docs_page`.`current_version` = `docs_project`.`current_version` AND `docs_page`.`suspended` = False )',}
                                                      ).select_related(depth = 2).order_by('people_count')
    
    
    projects = []
    joined_projects = Project.objects.filter(translators = request.user)
    for project in project_objects:
        joined = project in joined_projects
        progress = float(project.translated_paragraphs.count()) * 100 / float(project.effective_paragraphs.count())
        projects.append((project, joined, progress))
    
    recent_versions = Version.objects.filter(changed = True).order_by('-revision')
    recent_versions_and_changes = []
    for v in recent_versions:
        changes = PageChange.objects.filter(version = v).select_related(depth = 1)
        recent_versions_and_changes.append((v,changes))
    projects_count = Project.objects.count()
    last_updated = Version.objects.filter(changed = True).latest('created').created
    people_count = User.objects.filter(joined_projects__isnull=False).distinct().count()
    translations_count = Translation.objects.filter(translator = request.user).count()
    effective_translations_count = Translation.effectives.filter(translator = request.user).count()
    title = "Project List"
    return render_to_response('docs/admin/project_list.html',locals(), context_instance = RequestContext(request))

@login_required
def project_join_quit(request, project_slug, action):
    project_object = get_object_or_404(Project, slug = project_slug)
    joined = request.user in project_object.translators.all()
    
    if (action=='join' and joined) or (action=='quit' and not joined):
        return HttpResponseRedirect(project_object.admin_url)
    
    if request.method == 'POST':
        if action=='join':
            project_object.translators.add(request.user)
        elif action=='quit':
            project_object.translators.remove(request.user)
        return HttpResponseRedirect(project_object.admin_url)
    
    title = "Confirmation of %s Project %s" % (action.title(), project_object)
    return render_to_response('docs/admin/confirmation.html',locals(), context_instance = RequestContext(request))

    
@login_required
def project_page_list(request, project_slug):
    project_object = get_object_or_404(Project, slug = project_slug)
    total_pages_count = project_object.effective_pages.count()
    effective_paragraphs_count = project_object.effective_paragraphs.count()
    translated_paragraphs_count = project_object.translated_paragraphs.count()
    translated_percent = float(translated_paragraphs_count) * 100 / float(effective_paragraphs_count)
    people_count = project_object.translators.count()

#    content_order = ['','intro','topics','howto','faq','ref','misc','releases','internals','obsolete']
#    effective_pages = project_object.effective_pages.extra(select = {'paragraphs_count': 'SELECT COUNT(*) FROM `docs_paragraph` WHERE (`docs_paragraph`.`page_id` = `docs_page`.`id` AND `docs_paragraph`.`current_version` = %s )' % project_object.current_version,
#                                                                    'translated_count': 'SELECT COUNT(*) FROM `docs_paragraph` WHERE (`docs_paragraph`.`page_id` = `docs_page`.`id` AND `docs_paragraph`.`current_version` = %s AND `docs_paragraph`.`translation_id` IS NOT NULL)' % project_object.current_version,}
#                                                                    ).order_by('path')
#
#    content_dict = {}
#    for page in effective_pages:
#        dir, base = os.path.split(page.path)
#        key = dir.split('/')[0] or ""
#        items = content_dict.setdefault(key,[])
#        progress = float(page.translated_count) * 100 / float(page.paragraphs_count)
#        items.append((page, progress))
#        
#    if project_object.content_order:
#        content_order = [''] + project_object.content_order.split()
#        content = sorted(content_dict.items(), key = lambda(k,v):content_order.index(k))
#    
    recent_versions = project_object.versions.filter(changed = True).order_by('-revision')
    recent_versions_and_changes = []
    for v in recent_versions:
        changes = PageChange.objects.filter(version = v).select_related(depth = 1)
        recent_versions_and_changes.append((v,changes))
        
    title = "%s | Documentation contents" % project_object
    return render_to_response('docs/admin/project_page_list.html',locals(), context_instance = RequestContext(request))


@login_required
def project_versions(request, project_slug):

    title = "Project List"
    return render_to_response('docs/admin/project_list.html',locals(), context_instance = RequestContext(request))



@login_required
def page(request, project_slug, page_slug):
    if not path.endswith(".txt"):
        return index(request, path)
    page_object = get_object_or_404(Page, path = path)
    page_group, group_created = Group.objects.get_or_create(name = page_object.path)
    review_group, review_group_created = Group.objects.get_or_create(name = "review group")
    user_joined = request.user in page_group.user_set.all()
    user_in_review_group = request.user in review_group.user_set.all()
    if 'review' in request.GET:
        review_paragraph_object = get_object_or_404(page_object.get_paragraphs().filter(translation__isnull = False), id = int(request.GET.get('review')))
        if not user_in_review_group:
            raise Http404()
        else:
            review_paragraph_object.reviewed = True
            review_paragraph_object.reviewed_by = request.user
            review_paragraph_object.save()
            return HttpResponseRedirect(review_paragraph_object.admin_url())
    paragraph_objects = page_object.get_paragraphs().order_by('ordinal')
    paragraphs = []
    for p in paragraph_objects:
        paragraphs.append((p, user_in_review_group or (user_joined and not p.reviewed)))
    title = "Translating Page %s" % page_object.path
    return render_to_response('docs/admin/page.html',locals(), context_instance = RequestContext(request))

@login_required
def page_change(request, project_slug, page_slug):
    pass

@login_required
def paragraph_translation(request, paragraph_id):
    paragraph = get_object_or_404(Paragraph, id = paragraph_id)
    page_group, group_created = Group.objects.get_or_create(name = paragraph.page.path)
    review_group, review_group_created = Group.objects.get_or_create(name = "review group")
    user_joined = request.user in page_group.user_set.all()
    user_in_review_group = request.user in review_group.user_set.all()
    if not (user_joined or user_in_review_group):
        return HttpResponse(paragraph.original)
    
    if request.method == 'POST':
        content = request.POST.get('new_content').strip()
        new_translation = Translation(paragraph = paragraph, inherited_from = paragraph.translation,
                                      translator = request.user, content = content, ip = request.META['REMOTE_ADDR'])
        new_translation.save()
        return HttpResponse(content)
    else:
        return HttpResponse(paragraph.original)

@login_required
def paragraph_comment(request, paragraph_id):
    paragraph = get_object_or_404(Paragraph, id = paragraph_id)
    page_group, group_created = Group.objects.get_or_create(name = paragraph.page.path)
    review_group, review_group_created = Group.objects.get_or_create(name = "review group")
    user_joined = request.user in page_group.user_set.all()
    user_in_review_group = request.user in review_group.user_set.all()
    if not (user_joined or user_in_review_group):
        return HttpResponse("")
    
    if request.method == 'POST':
        content = request.POST.get('new_content').strip()
        if content == "":
            return HttpResponse("Don't submit empty comment.")
        else:
            paragraph.comment = (paragraph.comment + "\n%s : %s" % (request.user, content)).strip()
            paragraph.save()
            return HttpResponse("Saved, refresh to see changes.")
    else:
        return HttpResponse("")

@login_required
def page_changeold(request, path):
    page_object = get_object_or_404(Page, path = path)
    page_changes = page_object.changes.order_by('-created')
    page_group, group_created = Group.objects.get_or_create(name = page_object.path)
    user_joined = request.user in page_group.user_set.all()
    
    title = "Changes of Page %s" % page_object.path
    return render_to_response('docs/admin/page_change.html',locals(), context_instance = RequestContext(request))

@login_required
def paragraph_history(request, paragraph_id):
    paragraph_object = get_object_or_404(Paragraph, id = paragraph_id)
    page_object = paragraph_object.page
    page_group, group_created = Group.objects.get_or_create(name = page_object.path)
    user_joined = request.user in page_group.user_set.all()
    histories = paragraph_object.histories()
    
    title = "Changes of Paragraph %s" % paragraph_object.title
    return render_to_response('docs/admin/paragraph_history.html',locals(), context_instance = RequestContext(request))

@login_required
def people_list(request):
    people = User.objects.filter(pages__isnull = False).distinct()
    people_translations = []
    for u in people:
        ts = u.translations.all()
        effective_ts = ts.filter(inherited_translations__isnull = True)
        people_translations.append((u,ts.count(),effective_ts))
    people_translations.sort(key = lambda e: e[1], reverse = True)
    print people_translations
    title = "People List"
    return render_to_response('docs/admin/people_list.html',locals(), context_instance = RequestContext(request))

@login_required
def people(request, username):
    user_object = get_object_or_404(User, username = username)
    translations = []
    pages = user_object.pages.all().order_by('path')
    for page in pages:
        paragraphs = page.get_paragraphs().filter(translation__translator = user_object)
        translations.append((page, paragraphs))
    title = "Translations of People %s" % user_object
    return render_to_response('docs/admin/people.html',locals(), context_instance = RequestContext(request))


@login_required
def versions(request):
    version_objects = Version.objects.order_by('revision')
    recent_versions_and_changes = []
    for v in version_objects:
        changes = PageChange.objects.filter(version = v).select_related(depth = 1)
        recent_versions_and_changes.append((v,changes))
    title = "Changes of Versions"
    return render_to_response('docs/admin/versions.html',locals(), context_instance = RequestContext(request))

#@login_required
#def page_join(request, path):
#    page_object = get_object_or_404(Page, path = path)
#    page_group, group_created = Group.objects.get_or_create(name = page_object.path)
#    if request.user in page_group.user_set.all():
#        return HttpResponseRedirect(page_object.admin_url())
#    
#    if request.method == 'POST':
#        page_group.user_set.add(request.user)
#        return HttpResponseRedirect(page_object.admin_url())
#    join_confirmation = True
#    title = "Confirmation of Join Page %s" % page_object.path
#    return render_to_response('docs/admin/confirmation.html',locals(), context_instance = RequestContext(request))
#
#@login_required
#def page_quit(request, path):
#    page_object = get_object_or_404(Page, path = path)
#    page_group, group_created = Group.objects.get_or_create(name = page_object.path)
#    if request.user not in page_group.user_set.all():
#        return HttpResponseRedirect(page_object.admin_url())
#    
#    if request.method == 'POST':
#        page_group.user_set.remove(request.user)
#        return HttpResponseRedirect(page_object.admin_url())
#    quit_confirmation = True
#    title = "Confirmation of Quit Page %s" % page_object.path
#    return render_to_response('docs/admin/confirmation.html',locals(), context_instance = RequestContext(request))